package com.ruslan.magaz.web;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.ruslan.magaz.domain.Address;
import com.ruslan.magaz.domain.Customer;
import com.ruslan.magaz.domain.User;
import com.ruslan.magaz.service.UserService;

@Controller
@RequestMapping("/customer")
public class CustomerController {
	
	public static final int MAX_ADDRESSSES = 5; 
	@Autowired
	private UserService userService;
	

	@ModelAttribute("customers")
	 public List<Customer> getAllCustomers() {
	  return userService.getAllCustomers();
	 }
	
	 @ModelAttribute("addresses")
	 public List<Address> getAllAddresses(HttpServletRequest req) {
		HttpSession session = req.getSession(false);
		int currentUserId = (Integer) session.getAttribute("userId");
	  return userService.getAllAddressesForUser(currentUserId);
	 }
	
	@InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        sdf.setLenient(true);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }
	
	private boolean wrongAddress(HttpServletRequest req,int id){
		HttpSession session = req.getSession(false);
		int currentUserId = (Integer) session.getAttribute("userId");
		User user = userService.getUserById(currentUserId);
		if (user == null){
			return true;
		}
	    Customer customer = user.getCustomer();
	    if (customer == null){
			return true;
		}
		for (Address address:customer.getAddresses()){
        	if (address.getAddressId() == id){
        		return false;
        	}
        }
		return true;
	}
	 

	 @RequestMapping(value="/edit", method = RequestMethod.POST)
	    public String editCustomerPost(HttpServletRequest req, HttpServletResponse res, Model model, @Valid @ModelAttribute("customer") Customer customer, BindingResult bindingResult) throws ServletException, IOException{
				 if(bindingResult.hasErrors()){
					 Map< String, String > genders = new HashMap<String, String>();  
					 genders.put("true", "male");  
					 genders.put("false", "female");  
					 model.addAttribute("genderMap", genders);  
					 return"customerEdit";
				 }
		 		userService.editCustomer(customer);
		 		model.addAttribute("customers", getAllCustomers());
		 		return "redirect:/customer/";

		  }
	 
	 @RequestMapping(value="/edit", method = RequestMethod.GET)
	    public String editCustomer(HttpServletRequest req, HttpServletResponse res, Model model) throws ServletException, IOException{
				HttpSession session = req.getSession(false);
		        int currentUserId = (Integer) session.getAttribute("userId");
		        Customer customer = userService.getUserById(currentUserId).getCustomer();
			    model.addAttribute("customer", customer);
			    Map< String, String > genders = new HashMap<String, String>();  
		        genders.put("true", "male");  
		        genders.put("false", "female");  
		        model.addAttribute("genderMap", genders);  
			 	return "tiles/customerEdit";

		  }
	 @RequestMapping(value="", method = RequestMethod.GET)
	    public String showCustomer(HttpServletRequest req, HttpServletResponse res, Model model) throws ServletException, IOException{
				HttpSession session = req.getSession(false);
		        int currentUserId = (Integer) session.getAttribute("userId");
		        Customer customer = userService.getUserById(currentUserId).getCustomer();
		        Address shippingAddress = userService.shippingAddressForCustomer(customer);
		        if (shippingAddress ==null){
		        	model.addAttribute("address", new Address());
		        }else{
		        	model.addAttribute("address", shippingAddress);
		        }
			    model.addAttribute("customer", customer);
			    System.out.println("something");
			 	return "tiles/customerInfo";
		  }
	 
		  
	 @RequestMapping(value="/address/fav", method = RequestMethod.GET)
	    public String favAddress(HttpServletRequest req, HttpServletResponse res, @RequestParam int id, Model model) throws ServletException, IOException{

			 if (wrongAddress(req, id)){
				 return "redirect:/home";
			 }
			HttpSession session = req.getSession(false);
			int currentUserId = (Integer) session.getAttribute("userId");
			User user = userService.getUserById(currentUserId);
	        Customer customer = user.getCustomer();
	        customer.setShippingAddressId(id);
	        userService.editCustomer(customer);
	        model.addAttribute("customer", customer);
			return "redirect:/customer/";
		  }
	
	@RequestMapping(value="/address/addressForm", method = RequestMethod.POST)
    public String addressPost(HttpServletRequest req, HttpServletResponse res, Model model, @Valid @ModelAttribute("address") Address address, BindingResult bindingResult) throws ServletException, IOException{
		if(bindingResult.hasErrors()){
			 return"tiles/addressForm";
		}
		HttpSession session = req.getSession(false);
		if (address.getAddressId()==0){
			int currentUserId = (Integer) session.getAttribute("userId");
	        User user = userService.getUserById(currentUserId);
	        Customer customer = user.getCustomer();
	        address.setCustomer(customer);
			userService.addAddress(currentUserId, address);
		}else{
			userService.editAddress(address);
		}
		List<Address> addresses = getAllAddresses(req);
		model.addAttribute("addresses", addresses);
 		return "redirect:/customer/address";
	  }
 
	
	@RequestMapping(value="/address/add", method = RequestMethod.GET)
    public String addAddress(HttpServletRequest req, HttpServletResponse res, Model model) throws ServletException, IOException{
	 	HttpSession session = req.getSession(false);
	 	if (getAllAddresses(req).size()>=MAX_ADDRESSSES){
	 		return "redirect:/customer/address";
	 	}
		if (session == null){
			(res).sendError(403);
		}else{
	        Address address = new Address();
	        address.setAddressId(0);
		    model.addAttribute("address", address);
//		    model.addAttribute("new", true);
		}
		return "tiles/addressForm";
	  }
	
	@RequestMapping(value="/address/edit", method = RequestMethod.GET)
    public String editAddress(HttpServletRequest req, HttpServletResponse res, @RequestParam Integer id, Model model) throws ServletException, IOException{
		if (wrongAddress(req, id)){
        	return "redirect:/home";
        }
		Address address = userService.getAddressById(id);
		model.addAttribute("address", address);
		return "tiles/addressForm";
	}
	
	@RequestMapping(value="/address/remove", method = RequestMethod.GET)
    public String removeAddress(HttpServletRequest req, HttpServletResponse res, @RequestParam Integer id, Model model) throws ServletException, IOException{
		if (wrongAddress(req, id)){
			return "redirect:/home";
		}
		Address address = userService.getAddressById(id);
		userService.removeAddress(address);
		model.addAttribute("addresses", getAllAddresses(req));
		model.addAttribute("showAdd", true);
		return "tiles/addresses";
	}
	
	@RequestMapping(value="/address", method = RequestMethod.GET)
    public String showAddresses(HttpServletRequest req, HttpServletResponse res, Model model) throws ServletException, IOException{
		List<Address> addresses = getAllAddresses(req);
		if (addresses.size()>=MAX_ADDRESSSES){
	 		model.addAttribute("showAdd", false);
	 	}else{
	 		model.addAttribute("showAdd", true);
	 	}
		model.addAttribute("addresses", addresses);
		return "tiles/addresses";
	}
	
	

}
